# 计算器
from datetime import time, datetime
from tkinter import ttk
from tkinter import *
import tkinter as tk
from tkinter import messagebox
import os
#  pyinstaller -F manage.py --hidden-import tkinter --noconsole
# import tkinter.messagebox


class PlaceholderEntry(tk.Entry):
    def __init__(self, master=None, placeholder="", **kwargs):
        super().__init__(master, **kwargs)
        self.placeholder = placeholder
        self.default_fg_color = self['fg']
        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)
        self.put_placeholder()

    def put_placeholder(self):
        self.insert(0, self.placeholder)
        self['fg'] = 'grey'

    def on_focus_in(self, event):
        if self['fg'] == 'grey':
            self.delete('0', 'end')
            self['fg'] = self.default_fg_color

    def on_focus_out(self, event):
        if not self.get():
            self.put_placeholder()



class Application(Frame):
    """GUI application that manages a simple inventory"""
    def __init__(self, master):
        """Initialize the frame"""
        super(Application, self).__init__(master)
        # 创建一个文件夹
        if not os.path.exists(r"D://记账"):
            os.mkdir(r"D://记账")
        # 判断文件是否存在
        if not os.path.exists(r"D://记账/data.txt"):
            # 创建一个文件
            with open(r"D://记账/data.txt", "w") as f:
                pass

        # 创建一个消费记录文件
        if not os.path.exists(r"D://记账/consume.txt"):
            # 创建一个文件
            with open(r"D://记账/consume.txt", "w") as f:
                f.write("消费金额   消费说明    消费时间\n")

        if not os.path.exists(r"D://记账/recharge.txt"):
            # 创建一个文件
            with open(r"D://记账/recharge.txt", "w") as f:
                f.write("充值金额   充值说明   充值时间\n")


        self.pack()
        self.create_widgets()

    def create_widgets(self):
        """Create widgets to get product information and to display results."""

        input_frame = tk.Frame(self)
        input_frame.pack(fill=tk.X, padx=5, pady=5)

        # 在 Frame 容器中添加输入框
        self.input_box = PlaceholderEntry(input_frame, placeholder="增加存款", width=15)
        self.input_box.pack(side=tk.LEFT, padx=5, pady=5)

        # 充值说明
        self.recharge_explain = PlaceholderEntry(input_frame, placeholder="充值说明", width=15)
        self.recharge_explain.pack(side=tk.LEFT, padx=5, pady=5)

        # 在 Frame 容器中添加按钮
        self.add_button = Button(input_frame, text="确定", command=self.add_money,width=10)
        self.add_button.pack(side=tk.RIGHT, padx=1, pady=2)



        # 消费金额
        self.contant_frame = tk.Frame(self)
        self.contant_frame.pack(fill=tk.X, padx=5, pady=5)
        self.contant_frame.pack(fill=tk.X, padx=1, pady=2)
        self.consume_box = PlaceholderEntry(self.contant_frame, placeholder="消费金额",width=15)
        self.consume_box.pack(side=tk.LEFT, padx=5, pady=5)
        self.consume_explain = PlaceholderEntry(self.contant_frame, placeholder="说明",width=15)
        self.consume_explain.pack(side=tk.LEFT, padx=5, pady=5)
        # 消费按钮
        self.consume_button = Button(self.contant_frame, text="确定", command=self.consume_money, width=10)
        self.consume_button.pack(side=tk.RIGHT, padx=1, pady=2)



        # 存款展示
        self.result_label = Label(self, text="0")
        with open(r"D://记账/data.txt", "r") as f:
            self.result_label.config(text="我的存款金额：" + f.read())
        self.result_label.pack( side=tk.BOTTOM, padx=5, pady=5)

        # 打开文件资源管理器
        self.open_file_button = Button(self, text="打开流水账", command=self.open_file_explorer)
        self.open_file_button.pack(side=tk.BOTTOM, padx=5, pady=5)



        # self.result = Entry(self)
        # self.result.config(state='readonly')
        # self.result.grid(row=2, column=0,columnspan=4,sticky=EW,)

    def add_money(self):
        """Add the product to the inventory."""
        # 这里可以添加处理增加存款的逻辑
        result = messagebox.askokcancel("提示", "请确认您是否增加存款？")
        if result:
            with open(r"D://记账/data.txt", "a") as data:
                with open(r"D://记账/data.txt", "r") as f:
                    a = f.read().strip()
                    b = self.input_box.get().strip()
                    try:
                        result = int(b)
                        # 移动文件指针到特定位置（例如，文件开头）
                        data.seek(0)

                        # 截断文件，从当前指针位置开始
                        data.truncate()
                        sum = ''
                        if a:
                            sum = str(int(a)+result)
                            data.write(sum)
                        else:
                            sum = str(result)
                            data.write(sum)
                        self.result_label.config(text="我的存款金额：" + sum)
                        self.input_box.delete(0, 'end')
                        with open(f'D://记账/recharge.txt', 'a') as bf:
                            time_consume = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
                            bf.write(f"{result}  { self.recharge_explain.get().strip() if self.recharge_explain.get() else ''}  {time_consume}\n")
                    except ValueError:
                        messagebox.showerror("错误", "请输入数字!")
                        return


    def consume_money(self):
        """Add the money    """
        # 这里可以添加处理消费的逻辑
        result = messagebox.askokcancel("提示", "请确认您是否已经消费？")
        if result:
            try:
                # 消费金额
                consume = int(self.consume_box.get().strip())
                # 消费说明
                explain = self.consume_explain.get().strip()
                if not consume:
                    messagebox.showerror("错误", "请输入消费金额!")
                    return
                else:
                    with open(r"D://记账/data.txt", "r") as f:
                        a = f.read().strip()
                        b = int(a) - int(consume)
                        if b < 0:
                            messagebox.showerror("错误", "您的存款不足!")
                            return
                        with open(r"D://记账/data.txt", "w") as data:
                            data.write(str(b))
                            self.result_label.config(text="我的存款金额：" + str(b))
                        with open(r"D://记账/consume.txt", "a") as consume_a:
                            time_consume =  datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
                            consume_a.write(str(consume) + "   " + explain + "    " +  time_consume + "\n")
                    # 清除输入框
                    self.consume_box.delete(0, 'end')
                    self.consume_explain.delete(0, 'end')
            except ValueError:
                messagebox.showerror("错误", "请输入数字!")
                return

    def open_file_explorer(self):
        """Open the file resource manager."""
        os.startfile(r"D://记账")



if __name__ == '__main__':
    root = Tk()
    root.title("记账小程序")
    root.geometry("250x160+500+250")
    root.iconphoto(False, tk.PhotoImage(file=r"imgs/girls.gif"))
    app = Application(root)
    root.mainloop()
